﻿/* Copyright 2007-2008 dnAnalytics Project.
 *
 * Contributors to this file:
 * Jurgen Van Gael
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this 
 *   list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * * Neither the name of the dnAnalytics Project nor the names of its contributors
 *   may be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using dnAnalytics.Properties;

namespace dnAnalytics.Statistics.Distributions
{
    /// <summary>
    /// The discrete uniform distribution is a distribution over integers. The distribution
    /// is parameterized by a lower and upper bound (both inclusive).
    /// </summary>
    /// <remarks>The distribution will use the <see cref="System.Random"/> by default. 
    /// Users can set the random number generator by using the <see cref="RandomNumberGenerator"/> property.
    /// 
    /// The statistics classes will check all the incoming parameters whether they are in the allowed
    /// range. This might involve heavy computation. Optionally, by setting Control.CheckDistributionParameters
    /// to false, all parameter checks can be turned off.</remarks>
    public class DiscreteUniform : IDiscreteDistribution
    {
        /// <summary>
        /// The distribution's lower bound.
        /// </summary>
        private readonly int mLower;

        /// <summary>
        /// The distribution's upper bound.
        /// </summary>
        private readonly int mUpper;

        /// <summary>
        /// Construct a new discrete uniform distribution.
        /// </summary>
        /// <param name="lower">Lower bound.</param>
        /// <param name="upper">Upper bound; must be at least as large as <paramref name="lower"/>.</param>
        public DiscreteUniform(int lower, int upper)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(lower, upper);
            }

            mLower = lower;
            mUpper = upper;
            RandomNumberGenerator = new System.Random();
        }

        /// <summary>
        /// A string representation of the distribution.
        /// </summary>
        public override string ToString()
        {
            return "DiscreteUniform(Lower = " + mLower + ", Upper = " + mUpper + ")";
        }

        #region IDistribution Members

        /// <summary>
        /// The mean of the distribution.
        /// </summary>
        /// <value></value>
        public double Mean
        {
            get { return (mLower + mUpper)/2.0; }
        }

        /// <summary>
        /// The variance of the distribution.
        /// </summary>
        /// <value></value>
        public double Variance
        {
            get { return ((mUpper - mLower + 1.0)*(mUpper - mLower + 1.0) - 1.0)/12.0; }
        }

        /// <summary>
        /// The standard deviation of the distribution.
        /// </summary>
        /// <value></value>
        public double StdDev
        {
            get { return System.Math.Sqrt(((mUpper - mLower + 1.0)*(mUpper - mLower + 1.0) - 1.0)/12.0); }
        }

        /// <summary>
        /// The entropy of the distribution.
        /// </summary>
        /// <value></value>
        public double Entropy
        {
            get { return System.Math.Log(mUpper - mLower + 1.0); }
        }

        /// <summary>
        /// Gets or sets the random number generator.
        /// </summary>
        /// <value>The random number generator used to generate a random sample.</value>
        public System.Random RandomNumberGenerator { get; set; }

        #endregion

        #region IDiscreteDistribution Members

        /// <summary>
        /// The mode of the distribution.
        /// </summary>
        /// <value></value>
        public int Mode
        {
            get { return (int) System.Math.Round((mLower + mUpper)/2.0); }
        }

        /// <summary>
        /// The median of the distribution.
        /// </summary>
        /// <value></value>
        public int Median
        {
            get { throw new Exception("Not yet implemented."); }
        }

        /// <summary>
        /// Computes values of the probability mass function.
        /// </summary>
        /// <param name="k">The location in the domain where we want to evaluate the probability mass function.</param>
        /// <returns></returns>
        public double Probability(int k)
        {
            return 1.0/(mUpper - mLower + 1);
        }

        /// <summary>
        /// Samples a uniformly distributed random variable.
        /// </summary>
        public int Sample()
        {
            return DoSample(RandomNumberGenerator, mLower, mUpper);
        }

        /// <summary>
        /// Samples an array of uniformly distributed random variables.
        /// </summary>
        /// <param name="n">The number of variables needed.</param>
        public int[] Sample(int n)
        {
            return DoSample(RandomNumberGenerator, n, mLower, mUpper);
        }

        #endregion

        /// <summary>
        /// Samples a uniformly distributed random variable.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="lower">The lower bound of the uniform random variable.</param>
        /// <param name="upper">The upper bound of the uniform random variable.</param>
        public static int Sample(System.Random rnd, int lower, int upper)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(lower, upper);
            }

            return DoSample(rnd, lower, upper);
        }

        /// <summary>
        /// Samples an array of uniformly distributed random variables.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="n">The number of variables needed.</param>
        /// <param name="lower">The lower bound of the uniform random variable.</param>
        /// <param name="upper">The upper bound of the uniform random variable.</param>
        public static int[] Sample(System.Random rnd, int n, int lower, int upper)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(lower, upper);
            }

            return DoSample(rnd, n, lower, upper);
        }

        private static void CheckParameters(double lower, double upper)
        {
            if (upper < lower)
            {
                throw new ArgumentException(Resources.UpperMustBeAtleastAsLargeAsLower);
            }
        }

        private static int DoSample(System.Random rnd, int lower, int upper)
        {
            return rnd.Next()%(upper - lower + 1) + lower;
        }

        private static int[] DoSample(System.Random rnd, int n, int lower, int upper)
        {
            int[] arr = new int[n];
            for (int i = 0; i < n; i++)
            {
                arr[i] = DoSample(rnd, lower, upper);
            }
            return arr;
        }
    }
}